<script setup lang="ts">
import {cloneDeep, initPageQuery} from "@/utils/common-fn";
import {FormInstance} from "element-plus";
import {Ref} from "vue";
import {FileVo} from "@/api/common/file/types";
import {getFileListApi, getFoldersApi} from "@/api/common/file";
import XImageView from "@/components/MyComponent/XImageView.vue";
import XSelectBase from "@/components/MyComponent/XSelectBase.vue";

/**
 * table
 */
    // table数据
let tableData: Ref<FileVo[]> = ref([])
/**
 * 搜索和分页
 */
// 总数
const total = ref(0)
// 搜索ref
const searchRef = ref<FormInstance>()
const initQuery: Partial<PageQuery<FileVo>> = {order: {size: 'asc'}}
// 分页信息,以及查询条件,用于发送api
const queryData = reactive(initPageQuery<FileVo>(cloneDeep(initQuery)))
const options: Ref<{ folder: string }[]> = ref([])

// 获取列表
async function getList() {
  [tableData.value, total.value] = await getFileListApi(queryData);
}

// 重置搜索
async function resetSearch(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.resetFields()
  queryData.query = {}
  await nextTick()
  await getList()
}

// 根据文件大小计算文件宽度
function calcWidth(size: number): string {
  // 100Kb一下, 4em
  const kbSize = size / 1024
  if (kbSize < 50) {
    return '5em'
  } else {
    return `calc(${0.04 * kbSize}% + 5em)`
  }
}

watch([() => queryData.pageSize, () => queryData.currentPage], async () => {
  await getList()
})
// 载入查询
onMounted(async () => {
  options.value = await getFoldersApi()
  await getList()
})
</script>

<template>
  <!--  查询 -->
  <x-card>
    <el-form :inline="true" :model="queryData.query" label-suffix=":" ref="searchRef" class="flex flex-items-center">
      <el-form-item label="文件夹" prop="folder">
        <x-select-base :options="options" value-key="folder" label-key="folder" v-model="queryData.query.folder"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch(searchRef)" circle>
          <i-ep-refresh-left/>
        </el-button>
      </el-form-item>
    </el-form>
  </x-card>
  <!--  表格-->
  <x-card>
    <div class="flex flex-wrap">
      <x-image-view fit="contain" :width="calcWidth(item.size)" class="photo" v-for="item in tableData"
                    :url="item.shorUrl" :key="item.id"/>
    </div>
  </x-card>
  <!--  分页-->
  <x-card>
    <XPagination
        v-model:page-size="queryData.pageSize"
        v-model:current-page="queryData.currentPage"
        v-model:total="total"
    />
  </x-card>
</template>
<style scoped lang="scss">
.flex {

}

.photo {
  margin: 0.4em;
}

</style>